package com.hncj.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hncj.pojo.Article;
import com.hncj.pojo.Image;
import com.hncj.result.R;
import com.hncj.service.ArticleService;
import com.hncj.service.ImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/article")
public class articleController {

    @Autowired
    private ArticleService articleService;
    @Autowired
    private ImageService imageService;
    @Autowired
    private imageController imageControl;

    @PostMapping
    public R<Integer> insertArticle(@RequestBody Article s){
        s.setTime(LocalDateTime.now());
        articleService.save(s);
        return R.success(s.getId());
    }

    @PutMapping
    public R<String> updateArticle(@RequestBody Article s){

        s.setTime(LocalDateTime.now());

        return articleService.updateById(s)?R.success("更新成功") : R.error("更新失败");

    }

    @GetMapping("/{id}")
    public R<Article> getById(@PathVariable("id") Integer id){
        Article byId = articleService.getById(id);
        byId.setReadSum(byId.getReadSum()+1);
        articleService.updateById(byId);
        return R.success(byId);
    }

    @DeleteMapping
    public R<String> deleteById(@RequestBody int[] ids){
        for(int i : ids){
            LambdaQueryWrapper<Image> like = new LambdaQueryWrapper<>();
            like.eq(Image::getDependenceId,i);

            List<Image> list = imageService.list(like);

            String [] names=new String[list.size()];

            for (int j = 0; j < list.size(); j++) names[j]=list.get(j).getImage();

            imageControl.deleteImageByName(names);

            articleService.removeById(i);
        }
        return R.success("已删除");
    }

    @GetMapping("/list")
    public R<List<Article>> getList(){
        return R.success(articleService.list());
    }
}
